class YfWebSocket {

    constructor() {
        this.ws = null
        this.reConnect = false
        this.url = null
    }

    /**
     * 重连
     */
    reConnect = () => {
        this.reConnect = true
        this.initWebSocket().then(()=>{
            console.log('重连成功')
        })
    }

    /**
     * 初始化socket
     * @param url
     * @param onMsgHandler
     * @param onOpenHandler
     * @returns {Promise<any>}
     */
    initWebSocket = (url,onMsgHandler, onOpenHandler) => {
        //初始化 用于重连的时候重新调用
        if(!this.reConnect){
            this.onMsgHandler = onMsgHandler
            this.onOpenHandler = onOpenHandler
            this.url = url
        }
        return new Promise((resolve, reject) => {
            if (this.ws == null || this.reConnect) {
                //websocket存在
                if ('WebSocket' in window) {
                    this.ws = new WebSocket(this.url);
                    this.ws.binaryType = "arraybuffer";
                    //连接打开
                    this.ws.onopen = () => {
                        console.log('连接打开')
                        if (this.onOpenHandler) {
                            this.onOpenHandler();
                        } else {
                            console.log('没有处理消息回调')
                        }
                        resolve()
                    }
                    this.ws.onmessage = (evt) => {
                        console.log('收到一条消息')
                        if (this.onMsgHandler) {
                            this.onMsgHandler(evt.data);
                        } else {
                            console.log('没有处理消息回调')
                        }
                        // MsgCenter.handleMsg(evt)
                    }
                    this.ws.onclose = (evt) => {
                        console.log('socket close')
                        // this.initWebSocket(true)
                    }
                    this.ws.onerror = (evt) => {
                        // this.ws = new WebSocket(process.env.VUE_APP_SOCKETURL);
                        console.log('连接出错!' + evt)
                    }
                } else {
                    alert('浏览器不支持，采用Http直连方式')
                }
            }
        })

    }

    /**
     * 发送消息
     * @param msgBytes
     */
    sendMsg = (msgBytes) => {
        this.ws.send(msgBytes)
    }
}

export default new YfWebSocket()